package com.yyy.tcc.service.compensation;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ConcurrentRequestDemo {
    public static void main(String[] args) {
        // 创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                10,                       // 核心线程数
                100,                      // 最大线程数
                60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10000), // 队列容量10000
                new ThreadFactory() {    // 线程工厂
                    private final AtomicInteger threadNumber = new AtomicInteger(1);

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r, "transfer-thread-" + threadNumber.getAndIncrement());
                        t.setDaemon(true);
                        return t;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        // 模拟10万个并发请求同时到达
        CountDownLatch startSignal = new CountDownLatch(1);
        CountDownLatch doneSignal = new CountDownLatch(100000);

        // 提前创建100000个任务，准备同时提交
        for (int i = 0; i < 100000; i++) {
            final int taskId = i;
            new Thread(() -> {
                try {
                    // 等待统一启动信号
                    startSignal.await();

                    // 提交任务到线程池
                    executor.execute(() -> {
                        try {
                            System.out.println("Task-" + taskId +
                                    " executed by " + Thread.currentThread().getName());
                            Thread.sleep(100); // 模拟任务执行时间
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            doneSignal.countDown();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        // 发出启动信号，所有任务同时提交
        startSignal.countDown();
    }
}
